#include "compass.h"
#include <QtPlugin>
Q_EXPORT_PLUGIN2(compass, Compass); // first is target name in project file
Compass::Compass(QWidget *parent) : QGLWidget(parent), QFitsPlugin() {
	setFormat(QGLFormat(QGL::SampleBuffers));
	angle=0; // ccw from y-axis in degrees
	timer=0;
}
Compass::~Compass(){
	if(timer)
		delete timer;
}

// QGLWidget implementation
void Compass::initializeGL(){
	// Set up the rendering context, define display lists etc.:
	glClearColor(0.0, 0.0, 1.0, 1.0);
	glColor3f(1, 1, 1);
	glDisable(GL_DEPTH_TEST); // 2D
	glEnable(GL_MULTISAMPLE);

	timer = new QTimer(this);
	connect(timer, SIGNAL(timeout()), this, SLOT(timerCallback()));
	timer->start(50);
}

static double min(double a, double b){ return a<b?a:b; }
void Compass::resizeGL(int w, int h){
	//printf("size: %d, %d\n", w, h);
	if(w==0 || h==0)
		return;
	glMatrixMode (GL_PROJECTION);
	glLoadIdentity();
	glOrtho(-(double)w/min(w, h), (double)w/min(w, h), (double)h/min(w, h), -(double)h/min(w, h), 0, 1); // left, right, bottom, top, NEAR, FAR
	glMatrixMode (GL_MODELVIEW);
	// setup viewport, projection etc.:
	glViewport(0, 0, (GLint)w, (GLint)h);
	//glFrustum(...);
}

void Compass::paintGL(){
	glClear(GL_COLOR_BUFFER_BIT);
	glMatrixMode (GL_MODELVIEW);
	glLoadIdentity();
	renderText (0, -.6, 0, "N");
	glRotatef(angle, 0, 0, 1);

	glEnable(GL_MULTISAMPLE);
	glBegin(GL_QUADS);
		glVertex2f(0, 1);
		glVertex2f(.2, 0);
		glVertex2f(0, -1);
		glVertex2f(-.2, 0);
	glEnd();
	glDisable(GL_MULTISAMPLE);
}

void Compass::timerCallback(){
	angle+=1;
	if(angle>180)
		angle -= 180;
	updateGL();
}

// slots
/** slot receiving the azimuth anfle in degrees that the compass points to.
  */
void Compass::setAzimuth(double a){
	angle = a;
	timer->stop();
	updateGL();
}

// QWidget implementation
QSize Compass::minimumSizeHint() const{
	return QSize(50, 50);
}
QSize Compass::sizeHint() const{
	return QSize(100, 100);
}

int Compass::heightForWidth(int width) const{
	return width; // prefer square
}

void Compass::onInitialize(QObject *parent){
	printf("Initializing compass\n");
}

